<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="../Styles/sure3.css" rel="stylesheet" type="text/css"/>
    <link href="../Styles/base1.css" rel="stylesheet" type="text/css"/>
</head>

<body>
<div class="markdown-body entry-content" itemprop="text">
    <h1><a href="#generator-函数的语法"  class="anchor" id="user-content-generator-函数的语法">

    </a>Generator 函数的语法
    </h1>
    <h2><a href="#简介"  class="anchor" id="user-content-简介">

    </a>简介
    </h2>
    <h3><a href="#基本概念"  class="anchor" id="user-content-基本概念">

    </a>基本概念
    </h3>
    <p>Generator 函数是 ES6 提供的一种异步编程解决方案，语法行为与传统函数完全不同。本章详细介绍 Generator 函数的语法和 API，它的异步编程应用请看《Generator 函数的异步应用》一章。</p>
    <p>Generator 函数有多种理解角度。从语法上，首先可以把它理解成，Generator 函数是一个状态机，封装了多个内部状态。</p>
    <p>执行 Generator 函数会返回一个遍历器对象，也就是说，Generator 函数除了状态机，还是一个遍历器对象生成函数。返回的遍历器对象，可以依次遍历 Generator 函数内部的每一个状态。</p>
    <p>形式上，Generator 函数是一个普通函数，但是有两个特征。一是，<code>function</code>关键字与函数名之间有一个星号；二是，函数体内部使用<code>yield</code>表达式，定义不同的内部状态（<code>yield</code>在英语里的意思就是“产出”）。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">helloWorldGenerator</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>hello<span
                class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>world<span
                class="pl-pds">'</span></span>;
  <span class="pl-k">return</span> <span class="pl-s"><span class="pl-pds">'</span>ending<span
                class="pl-pds">'</span></span>;
}

<span class="pl-k">var</span> hw <span class="pl-k">=</span> <span class="pl-en">helloWorldGenerator</span>();</pre>
    </div>
    <p>上面代码定义了一个 Generator
        函数<code>helloWorldGenerator</code>，它内部有两个<code>yield</code>表达式（<code>hello</code>和<code>world</code>），即该函数有三个状态：hello，world
        和 return 语句（结束执行）。</p>
    <p>然后，Generator 函数的调用方法与普通函数一样，也是在函数名后面加上一对圆括号。不同的是，调用 Generator
        函数后，该函数并不执行，返回的也不是函数运行结果，而是一个指向内部状态的指针对象，也就是上一章介绍的遍历器对象（Iterator Object）。</p>
    <p>下一步，必须调用遍历器对象的<code>next</code>方法，使得指针移向下一个状态。也就是说，每次调用<code>next</code>方法，内部指针就从函数头部或上一次停下来的地方开始执行，直到遇到下一个<code>yield</code>表达式（或<code>return</code>语句）为止。换言之，Generator
        函数是分段执行的，<code>yield</code>表达式是暂停执行的标记，而<code>next</code>方法可以恢复执行。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-smi">hw</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> { value: 'hello', done: false }</span>

<span class="pl-smi">hw</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> { value: 'world', done: false }</span>

<span class="pl-smi">hw</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> { value: 'ending', done: true }</span>

<span class="pl-smi">hw</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> { value: undefined, done: true }</span></pre>
    </div>
    <p>上面代码一共调用了四次<code>next</code>方法。</p>
    <p>第一次调用，Generator 函数开始执行，直到遇到第一个<code>yield</code>表达式为止。<code>next</code>方法返回一个对象，它的<code>value</code>属性就是当前<code>yield</code>表达式的值<code>hello</code>，<code>done</code>属性的值<code>false</code>，表示遍历还没有结束。
    </p>
    <p>第二次调用，Generator 函数从上次<code>yield</code>表达式停下的地方，一直执行到下一个<code>yield</code>表达式。<code>next</code>方法返回的对象的<code>value</code>属性就是当前<code>yield</code>表达式的值<code>world</code>，<code>done</code>属性的值<code>false</code>，表示遍历还没有结束。
    </p>
    <p>第三次调用，Generator
        函数从上次<code>yield</code>表达式停下的地方，一直执行到<code>return</code>语句（如果没有<code>return</code>语句，就执行到函数结束）。<code>next</code>方法返回的对象的<code>value</code>属性，就是紧跟在<code>return</code>语句后面的表达式的值（如果没有<code>return</code>语句，则<code>value</code>属性的值为<code>undefined</code>），<code>done</code>属性的值<code>true</code>，表示遍历已经结束。
    </p>
    <p>第四次调用，此时 Generator 函数已经运行完毕，<code>next</code>方法返回对象的<code>value</code>属性为<code>undefined</code>，<code>done</code>属性为<code>true</code>。以后再调用<code>next</code>方法，返回的都是这个值。
    </p>
    <p>总结一下，调用 Generator 函数，返回一个遍历器对象，代表 Generator
        函数的内部指针。以后，每次调用遍历器对象的<code>next</code>方法，就会返回一个有着<code>value</code>和<code>done</code>两个属性的对象。<code>value</code>属性表示当前的内部状态的值，是<code>yield</code>表达式后面那个表达式的值；<code>done</code>属性是一个布尔值，表示是否遍历结束。
    </p>
    <p>ES6 没有规定，<code>function</code>关键字与函数名之间的星号，写在哪个位置。这导致下面的写法都能通过。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span class="pl-k">*</span> <span
            class="pl-en">foo</span>(<span class="pl-smi">x</span>, <span class="pl-smi">y</span>) { ··· }
<span class="pl-k">function</span> <span class="pl-k">*</span><span class="pl-en">foo</span>(<span
                class="pl-smi">x</span>, <span class="pl-smi">y</span>) { ··· }
<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">foo</span>(<span
                class="pl-smi">x</span>, <span class="pl-smi">y</span>) { ··· }
<span class="pl-k">function</span><span class="pl-k">*</span><span class="pl-en">foo</span>(<span
                class="pl-smi">x</span>, <span class="pl-smi">y</span>) { ··· }</pre>
    </div>
    <p>由于 Generator 函数仍然是普通函数，所以一般的写法是上面的第三种，即星号紧跟在<code>function</code>关键字后面。本书也采用这种写法。</p>
    <h3><a href="#yield-表达式"  class="anchor" id="user-content-yield-表达式">

    </a>yield 表达式
    </h3>
    <p>由于 Generator 函数返回的遍历器对象，只有调用<code>next</code>方法才会遍历下一个内部状态，所以其实提供了一种可以暂停执行的函数。<code>yield</code>表达式就是暂停标志。</p>
    <p>遍历器对象的<code>next</code>方法的运行逻辑如下。</p>
    <p>（1）遇到<code>yield</code>表达式，就暂停执行后面的操作，并将紧跟在<code>yield</code>后面的那个表达式的值，作为返回的对象的<code>value</code>属性值。</p>
    <p>（2）下一次调用<code>next</code>方法时，再继续往下执行，直到遇到下一个<code>yield</code>表达式。</p>
    <p>
        （3）如果没有再遇到新的<code>yield</code>表达式，就一直运行到函数结束，直到<code>return</code>语句为止，并将<code>return</code>语句后面的表达式的值，作为返回的对象的<code>value</code>属性值。
    </p>
    <p>（4）如果该函数没有<code>return</code>语句，则返回的对象的<code>value</code>属性值为<code>undefined</code>。</p>
    <p>需要注意的是，<code>yield</code>表达式后面的表达式，只有当调用<code>next</code>方法、内部指针指向该语句时才会执行，因此等于为 JavaScript 提供了手动的“惰性求值”（Lazy
        Evaluation）的语法功能。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>() {
  <span class="pl-k">yield</span>  <span class="pl-c1">123</span> <span class="pl-k">+</span> <span
                class="pl-c1">456</span>;
}</pre>
    </div>
    <p>上面代码中，<code>yield</code>后面的表达式<code>123 + 456</code>，不会立即求值，只会在<code>next</code>方法将指针移到这一句时，才会求值。</p>
    <p><code>yield</code>表达式与<code>return</code>语句既有相似之处，也有区别。相似之处在于，都能返回紧跟在语句后面的那个表达式的值。区别在于每次遇到<code>yield</code>，函数暂停执行，下一次再从该位置继续向后执行，而<code>return</code>语句不具备位置记忆的功能。一个函数里面，只能执行一次（或者说一个）<code>return</code>语句，但是可以执行多次（或者说多个）<code>yield</code>表达式。正常函数只能返回一个值，因为只能执行一次<code>return</code>；Generator
        函数可以返回一系列的值，因为可以有任意多个<code>yield</code>。从另一个角度看，也可以说 Generator 生成了一系列的值，这也就是它的名称的来历（英语中，generator 这个词是“生成器”的意思）。
    </p>
    <p>Generator 函数可以不用<code>yield</code>表达式，这时就变成了一个单纯的暂缓执行函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">f</span>() {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>执行了！<span
                class="pl-pds">'</span></span>)
}

<span class="pl-k">var</span> generator <span class="pl-k">=</span> <span class="pl-en">f</span>();

<span class="pl-c1">setTimeout</span>(<span class="pl-k">function</span> () {
  <span class="pl-smi">generator</span>.<span class="pl-c1">next</span>()
}, <span class="pl-c1">2000</span>);</pre>
    </div>
    <p>上面代码中，函数<code>f</code>如果是普通函数，在为变量<code>generator</code>赋值时就会执行。但是，函数<code>f</code>是一个 Generator 函数，就变成只有调用<code>next</code>方法时，函数<code>f</code>才会执行。
    </p>
    <p>另外需要注意，<code>yield</code>表达式只能用在 Generator 函数里面，用在其他地方都会报错。</p>
    <div class="highlight highlight-source-js"><pre>(<span class="pl-k">function</span> (){
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
})()
<span class="pl-c"><span class="pl-c">//</span> SyntaxError: Unexpected number</span></pre>
    </div>
    <p>上面代码在一个普通函数中使用<code>yield</code>表达式，结果产生一个句法错误。</p>
    <p>下面是另外一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> arr <span class="pl-k">=</span> [<span
            class="pl-c1">1</span>, [[<span class="pl-c1">2</span>, <span class="pl-c1">3</span>], <span
            class="pl-c1">4</span>], [<span class="pl-c1">5</span>, <span class="pl-c1">6</span>]];

<span class="pl-k">var</span> <span class="pl-en">flat</span> <span class="pl-k">=</span> <span
                class="pl-k">function</span><span class="pl-k">*</span> (<span class="pl-smi">a</span>) {
  <span class="pl-smi">a</span>.<span class="pl-c1">forEach</span>(<span class="pl-k">function</span> (<span
                class="pl-smi">item</span>) {
    <span class="pl-k">if</span> (<span class="pl-k">typeof</span> item <span class="pl-k">!==</span> <span
                class="pl-s"><span class="pl-pds">'</span>number<span class="pl-pds">'</span></span>) {
      <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">flat</span>(item);
    } <span class="pl-k">else</span> {
      <span class="pl-k">yield</span> item;
    }
  });
};

<span class="pl-k">for</span> (<span class="pl-k">var</span> f <span class="pl-k">of</span> <span
                class="pl-en">flat</span>(arr)){
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(f);
}</pre>
    </div>
    <p>上面代码也会产生句法错误，因为<code>forEach</code>方法的参数是一个普通函数，但是在里面使用了<code>yield</code>表达式（这个函数里面还使用了<code>yield*</code>表达式，详细介绍见后文）。一种修改方法是改用<code>for</code>循环。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> arr <span class="pl-k">=</span> [<span
            class="pl-c1">1</span>, [[<span class="pl-c1">2</span>, <span class="pl-c1">3</span>], <span
            class="pl-c1">4</span>], [<span class="pl-c1">5</span>, <span class="pl-c1">6</span>]];

<span class="pl-k">var</span> <span class="pl-en">flat</span> <span class="pl-k">=</span> <span
                class="pl-k">function</span><span class="pl-k">*</span> (<span class="pl-smi">a</span>) {
  <span class="pl-k">var</span> length <span class="pl-k">=</span> <span class="pl-smi">a</span>.<span class="pl-c1">length</span>;
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i <span class="pl-k">=</span> <span
                class="pl-c1">0</span>; i <span class="pl-k">&lt;</span> length; i<span class="pl-k">++</span>) {
    <span class="pl-k">var</span> item <span class="pl-k">=</span> a[i];
    <span class="pl-k">if</span> (<span class="pl-k">typeof</span> item <span class="pl-k">!==</span> <span
                class="pl-s"><span class="pl-pds">'</span>number<span class="pl-pds">'</span></span>) {
      <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">flat</span>(item);
    } <span class="pl-k">else</span> {
      <span class="pl-k">yield</span> item;
    }
  }
};

<span class="pl-k">for</span> (<span class="pl-k">var</span> f <span class="pl-k">of</span> <span
                class="pl-en">flat</span>(arr)) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(f);
}
<span class="pl-c"><span class="pl-c">//</span> 1, 2, 3, 4, 5, 6</span></pre>
    </div>
    <p>另外，<code>yield</code>表达式如果用在另一个表达式之中，必须放在圆括号里面。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">demo</span>() {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Hello<span
                class="pl-pds">'</span></span> <span class="pl-k">+</span> <span class="pl-k">yield</span>); <span
                class="pl-c"><span class="pl-c">//</span> SyntaxError</span>
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Hello<span
                class="pl-pds">'</span></span> <span class="pl-k">+</span> <span class="pl-k">yield</span> <span
                class="pl-c1">123</span>); <span class="pl-c"><span class="pl-c">//</span> SyntaxError</span>

  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Hello<span
                class="pl-pds">'</span></span> <span class="pl-k">+</span> (<span class="pl-k">yield</span>)); <span
                class="pl-c"><span class="pl-c">//</span> OK</span>
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Hello<span
                class="pl-pds">'</span></span> <span class="pl-k">+</span> (<span class="pl-k">yield</span> <span
                class="pl-c1">123</span>)); <span class="pl-c"><span class="pl-c">//</span> OK</span>
}</pre>
    </div>
    <p><code>yield</code>表达式用作函数参数或放在赋值表达式的右边，可以不加括号。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">demo</span>() {
  <span class="pl-en">foo</span>(<span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>a<span
                class="pl-pds">'</span></span>, <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>b<span
                class="pl-pds">'</span></span>); <span class="pl-c"><span class="pl-c">//</span> OK</span>
  <span class="pl-k">let</span> input <span class="pl-k">=</span> <span class="pl-k">yield</span>; <span
                class="pl-c"><span class="pl-c">//</span> OK</span>
}</pre>
    </div>
    <h3><a href="#与-iterator-接口的关系"  class="anchor" id="user-content-与-iterator-接口的关系">

    </a>与 Iterator 接口的关系
    </h3>
    <p>上一章说过，任意一个对象的<code>Symbol.iterator</code>方法，等于该对象的遍历器生成函数，调用该函数会返回该对象的一个遍历器对象。</p>
    <p>由于 Generator 函数就是遍历器生成函数，因此可以把 Generator 赋值给对象的<code>Symbol.iterator</code>属性，从而使得该对象具有 Iterator 接口。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> myIterable <span class="pl-k">=</span> {};
myIterable[<span class="pl-c1">Symbol</span>.<span class="pl-smi">iterator</span>] <span class="pl-k">=</span> <span
                class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
};

[<span class="pl-k">...</span>myIterable] <span class="pl-c"><span class="pl-c">//</span> [1, 2, 3]</span></pre>
    </div>
    <p>上面代码中，Generator 函数赋值给<code>Symbol.iterator</code>属性，从而使得<code>myIterable</code>对象具有了 Iterator
        接口，可以被<code>...</code>运算符遍历了。</p>
    <p>Generator 函数执行后，返回一个遍历器对象。该对象本身也具有<code>Symbol.iterator</code>属性，执行后返回自身。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>(){
  <span class="pl-c"><span class="pl-c">//</span> some code</span>
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">gen</span>();

g[<span class="pl-c1">Symbol</span>.<span class="pl-smi">iterator</span>]() <span class="pl-k">===</span> g
<span class="pl-c"><span class="pl-c">//</span> true</span></pre>
    </div>
    <p>上面代码中，<code>gen</code>是一个 Generator 函数，调用它会生成一个遍历器对象<code>g</code>。它的<code>Symbol.iterator</code>属性，也是一个遍历器对象生成函数，执行后返回它自己。
    </p>
    <h2><a href="#next-方法的参数"  class="anchor" id="user-content-next-方法的参数">

    </a>next 方法的参数
    </h2>
    <p>
        <code>yield</code>表达式本身没有返回值，或者说总是返回<code>undefined</code>。<code>next</code>方法可以带一个参数，该参数就会被当作上一个<code>yield</code>表达式的返回值。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">f</span>() {
  <span class="pl-k">for</span>(<span class="pl-k">var</span> i <span class="pl-k">=</span> <span class="pl-c1">0</span>; <span
                class="pl-c1">true</span>; i<span class="pl-k">++</span>) {
    <span class="pl-k">var</span> reset <span class="pl-k">=</span> <span class="pl-k">yield</span> i;
    <span class="pl-k">if</span>(reset) { i <span class="pl-k">=</span> <span class="pl-k">-</span><span
                class="pl-c1">1</span>; }
  }
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">f</span>();

<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value: 0, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value: 1, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>(<span class="pl-c1">true</span>) <span class="pl-c"><span
                class="pl-c">//</span> { value: 0, done: false }</span></pre>
    </div>
    <p>上面代码先定义了一个可以无限运行的 Generator
        函数<code>f</code>，如果<code>next</code>方法没有参数，每次运行到<code>yield</code>表达式，变量<code>reset</code>的值总是<code>undefined</code>。当<code>next</code>方法带一个参数<code>true</code>时，变量<code>reset</code>就被重置为这个参数（即<code>true</code>），因此<code>i</code>会等于<code>-1</code>，下一轮循环就会从<code>-1</code>开始递增。
    </p>
    <p>这个功能有很重要的语法意义。Generator 函数从暂停状态到恢复运行，它的上下文状态（context）是不变的。通过<code>next</code>方法的参数，就有办法在 Generator
        函数开始运行之后，继续向函数体内部注入值。也就是说，可以在 Generator 函数运行的不同阶段，从外部向内部注入不同的值，从而调整函数行为。</p>
    <p>再看一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">foo</span>(<span class="pl-smi">x</span>) {
  <span class="pl-k">var</span> y <span class="pl-k">=</span> <span class="pl-c1">2</span> <span class="pl-k">*</span> (<span
                class="pl-k">yield</span> (x <span class="pl-k">+</span> <span class="pl-c1">1</span>));
  <span class="pl-k">var</span> z <span class="pl-k">=</span> <span class="pl-k">yield</span> (y <span
                class="pl-k">/</span> <span class="pl-c1">3</span>);
  <span class="pl-k">return</span> (x <span class="pl-k">+</span> y <span class="pl-k">+</span> z);
}

<span class="pl-k">var</span> a <span class="pl-k">=</span> <span class="pl-en">foo</span>(<span class="pl-c1">5</span>);
<span class="pl-smi">a</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> Object{value:6, done:false}</span>
<span class="pl-smi">a</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> Object{value:NaN, done:false}</span>
<span class="pl-smi">a</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> Object{value:NaN, done:true}</span>

<span class="pl-k">var</span> b <span class="pl-k">=</span> <span class="pl-en">foo</span>(<span class="pl-c1">5</span>);
<span class="pl-smi">b</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value:6, done:false }</span>
<span class="pl-smi">b</span>.<span class="pl-c1">next</span>(<span class="pl-c1">12</span>) <span class="pl-c"><span
                class="pl-c">//</span> { value:8, done:false }</span>
<span class="pl-smi">b</span>.<span class="pl-c1">next</span>(<span class="pl-c1">13</span>) <span class="pl-c"><span
                class="pl-c">//</span> { value:42, done:true }</span></pre>
    </div>
    <p>上面代码中，第二次运行<code>next</code>方法的时候不带参数，导致 y 的值等于<code>2 * undefined</code>（即<code>NaN</code>），除以 3
        以后还是<code>NaN</code>，因此返回对象的<code>value</code>属性也等于<code>NaN</code>。第三次运行<code>Next</code>方法的时候不带参数，所以<code>z</code>等于<code>undefined</code>，返回对象的<code>value</code>属性等于<code>5
            + NaN + undefined</code>，即<code>NaN</code>。</p>
    <p>
        如果向<code>next</code>方法提供参数，返回结果就完全不一样了。上面代码第一次调用<code>b</code>的<code>next</code>方法时，返回<code>x+1</code>的值<code>6</code>；第二次调用<code>next</code>方法，将上一次<code>yield</code>表达式的值设为<code>12</code>，因此<code>y</code>等于<code>24</code>，返回<code>y
        /
        3</code>的值<code>8</code>；第三次调用<code>next</code>方法，将上一次<code>yield</code>表达式的值设为<code>13</code>，因此<code>z</code>等于<code>13</code>，这时<code>x</code>等于<code>5</code>，<code>y</code>等于<code>24</code>，所以<code>return</code>语句的值等于<code>42</code>。
    </p>
    <p>注意，由于<code>next</code>方法的参数表示上一个<code>yield</code>表达式的返回值，所以在第一次使用<code>next</code>方法时，传递参数是无效的。V8
        引擎直接忽略第一次使用<code>next</code>方法时的参数，只有从第二次使用<code>next</code>方法开始，参数才是有效的。从语义上讲，第一个<code>next</code>方法用来启动遍历器对象，所以不用带有参数。
    </p>
    <p>再看一个通过<code>next</code>方法的参数，向 Generator 函数内部输入值的例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">dataConsumer</span>() {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Started<span
                class="pl-pds">'</span></span>);
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span
                class="pl-pds">`</span>1. <span class="pl-s1"><span class="pl-pse">${</span><span
                class="pl-k">yield</span><span class="pl-pse">}</span></span><span class="pl-pds">`</span></span>);
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span
                class="pl-pds">`</span>2. <span class="pl-s1"><span class="pl-pse">${</span><span
                class="pl-k">yield</span><span class="pl-pse">}</span></span><span class="pl-pds">`</span></span>);
  <span class="pl-k">return</span> <span class="pl-s"><span class="pl-pds">'</span>result<span
                class="pl-pds">'</span></span>;
}

<span class="pl-k">let</span> genObj <span class="pl-k">=</span> <span class="pl-en">dataConsumer</span>();
<span class="pl-smi">genObj</span>.<span class="pl-c1">next</span>();
<span class="pl-c"><span class="pl-c">//</span> Started</span>
<span class="pl-smi">genObj</span>.<span class="pl-c1">next</span>(<span class="pl-s"><span
                class="pl-pds">'</span>a<span class="pl-pds">'</span></span>)
<span class="pl-c"><span class="pl-c">//</span> 1. a</span>
<span class="pl-smi">genObj</span>.<span class="pl-c1">next</span>(<span class="pl-s"><span
                class="pl-pds">'</span>b<span class="pl-pds">'</span></span>)
<span class="pl-c"><span class="pl-c">//</span> 2. b</span></pre>
    </div>
    <p>上面代码是一个很直观的例子，每次通过<code>next</code>方法向 Generator 函数输入值，然后打印出来。</p>
    <p>如果想要第一次调用<code>next</code>方法时，就能够输入值，可以在 Generator 函数外面再包一层。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span
            class="pl-en">wrapper</span>(<span class="pl-smi">generatorFunction</span>) {
  <span class="pl-k">return</span> <span class="pl-k">function</span> (<span class="pl-k">...</span><span class="pl-v">args</span>) {
    <span class="pl-k">let</span> generatorObject <span class="pl-k">=</span> <span
                class="pl-en">generatorFunction</span>(<span class="pl-k">...</span>args);
    <span class="pl-smi">generatorObject</span>.<span class="pl-c1">next</span>();
    <span class="pl-k">return</span> generatorObject;
  };
}

<span class="pl-k">const</span> <span class="pl-c1">wrapped</span> <span class="pl-k">=</span> <span class="pl-en">wrapper</span>(<span
                class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">`</span>First input: <span
                class="pl-s1"><span class="pl-pse">${</span><span class="pl-k">yield</span><span class="pl-pse">}</span></span><span
                class="pl-pds">`</span></span>);
  <span class="pl-k">return</span> <span class="pl-s"><span class="pl-pds">'</span>DONE<span
                class="pl-pds">'</span></span>;
});

<span class="pl-en">wrapped</span>().<span class="pl-c1">next</span>(<span class="pl-s"><span class="pl-pds">'</span>hello!<span
                class="pl-pds">'</span></span>)
<span class="pl-c"><span class="pl-c">//</span> First input: hello!</span></pre>
    </div>
    <p>上面代码中，Generator 函数如果不用<code>wrapper</code>先包一层，是无法第一次调用<code>next</code>方法，就输入参数的。</p>
    <h2><a href="#forof-循环"  class="anchor" id="user-content-forof-循环">

    </a>for...of 循环
    </h2>
    <p><code>for...of</code>循环可以自动遍历 Generator 函数时生成的<code>Iterator</code>对象，且此时不再需要调用<code>next</code>方法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span class="pl-k">*</span><span
            class="pl-en">foo</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">4</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">5</span>;
  <span class="pl-k">return</span> <span class="pl-c1">6</span>;
}

<span class="pl-k">for</span> (<span class="pl-k">let</span> v <span class="pl-k">of</span> <span
                class="pl-en">foo</span>()) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(v);
}
<span class="pl-c"><span class="pl-c">//</span> 1 2 3 4 5</span></pre>
    </div>
    <p>上面代码使用<code>for...of</code>循环，依次显示 5 个<code>yield</code>表达式的值。这里需要注意，一旦<code>next</code>方法的返回对象的<code>done</code>属性为<code>true</code>，<code>for...of</code>循环就会中止，且不包含该返回对象，所以上面代码的<code>return</code>语句返回的<code>6</code>，不包括在<code>for...of</code>循环之中。
    </p>
    <p>下面是一个利用 Generator 函数和<code>for...of</code>循环，实现斐波那契数列的例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">fibonacci</span>() {
  <span class="pl-k">let</span> [prev, curr] <span class="pl-k">=</span> [<span class="pl-c1">0</span>, <span
                class="pl-c1">1</span>];
  <span class="pl-k">for</span> (;;) {
    [prev, curr] <span class="pl-k">=</span> [curr, prev <span class="pl-k">+</span> curr];
    <span class="pl-k">yield</span> curr;
  }
}

<span class="pl-k">for</span> (<span class="pl-k">let</span> n <span class="pl-k">of</span> <span class="pl-en">fibonacci</span>()) {
  <span class="pl-k">if</span> (n <span class="pl-k">&gt;</span> <span class="pl-c1">1000</span>) <span class="pl-k">break</span>;
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(n);
}</pre>
    </div>
    <p>从上面代码可见，使用<code>for...of</code>语句时不需要使用<code>next</code>方法。</p>
    <p>利用<code>for...of</code>循环，可以写出遍历任意对象（object）的方法。原生的 JavaScript 对象没有遍历接口，无法使用<code>for...of</code>循环，通过 Generator
        函数为它加上这个接口，就可以用了。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">objectEntries</span>(<span class="pl-smi">obj</span>) {
  <span class="pl-k">let</span> propKeys <span class="pl-k">=</span> <span class="pl-c1">Reflect</span>.<span
                class="pl-en">ownKeys</span>(obj);

  <span class="pl-k">for</span> (<span class="pl-k">let</span> propKey <span class="pl-k">of</span> propKeys) {
    <span class="pl-k">yield</span> [propKey, obj[propKey]];
  }
}

<span class="pl-k">let</span> jane <span class="pl-k">=</span> { first<span class="pl-k">:</span> <span
                class="pl-s"><span class="pl-pds">'</span>Jane<span class="pl-pds">'</span></span>, last<span
                class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>Doe<span
                class="pl-pds">'</span></span> };

<span class="pl-k">for</span> (<span class="pl-k">let</span> [key, value] <span class="pl-k">of</span> <span
                class="pl-en">objectEntries</span>(jane)) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span
                class="pl-pds">`</span><span class="pl-s1"><span class="pl-pse">${</span>key<span
                class="pl-pse">}</span></span>: <span class="pl-s1"><span class="pl-pse">${</span>value<span
                class="pl-pse">}</span></span><span class="pl-pds">`</span></span>);
}
<span class="pl-c"><span class="pl-c">//</span> first: Jane</span>
<span class="pl-c"><span class="pl-c">//</span> last: Doe</span></pre>
    </div>
    <p>上面代码中，对象<code>jane</code>原生不具备 Iterator 接口，无法用<code>for...of</code>遍历。这时，我们通过 Generator
        函数<code>objectEntries</code>为它加上遍历器接口，就可以用<code>for...of</code>遍历了。加上遍历器接口的另一种写法是，将 Generator 函数加到对象的<code>Symbol.iterator</code>属性上面。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">objectEntries</span>() {
  <span class="pl-k">let</span> propKeys <span class="pl-k">=</span> <span class="pl-c1">Object</span>.<span
                class="pl-c1">keys</span>(<span class="pl-c1">this</span>);

  <span class="pl-k">for</span> (<span class="pl-k">let</span> propKey <span class="pl-k">of</span> propKeys) {
    <span class="pl-k">yield</span> [propKey, <span class="pl-c1">this</span>[propKey]];
  }
}

<span class="pl-k">let</span> jane <span class="pl-k">=</span> { first<span class="pl-k">:</span> <span
                class="pl-s"><span class="pl-pds">'</span>Jane<span class="pl-pds">'</span></span>, last<span
                class="pl-k">:</span> <span class="pl-s"><span class="pl-pds">'</span>Doe<span
                class="pl-pds">'</span></span> };

jane[<span class="pl-c1">Symbol</span>.<span class="pl-smi">iterator</span>] <span class="pl-k">=</span> objectEntries;

<span class="pl-k">for</span> (<span class="pl-k">let</span> [key, value] <span class="pl-k">of</span> jane) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span
                class="pl-pds">`</span><span class="pl-s1"><span class="pl-pse">${</span>key<span
                class="pl-pse">}</span></span>: <span class="pl-s1"><span class="pl-pse">${</span>value<span
                class="pl-pse">}</span></span><span class="pl-pds">`</span></span>);
}
<span class="pl-c"><span class="pl-c">//</span> first: Jane</span>
<span class="pl-c"><span class="pl-c">//</span> last: Doe</span></pre>
    </div>
    <p>除了<code>for...of</code>循环以外，扩展运算符（<code>...</code>）、解构赋值和<code>Array.from</code>方法内部调用的，都是遍历器接口。这意味着，它们都可以将
        Generator 函数返回的 Iterator 对象，作为参数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">numbers</span> () {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>
  <span class="pl-k">return</span> <span class="pl-c1">3</span>
  <span class="pl-k">yield</span> <span class="pl-c1">4</span>
}

<span class="pl-c"><span class="pl-c">//</span> 扩展运算符</span>
[<span class="pl-k">...</span><span class="pl-en">numbers</span>()] <span class="pl-c"><span class="pl-c">//</span> [1, 2]</span>

<span class="pl-c"><span class="pl-c">//</span> Array.from 方法</span>
<span class="pl-c1">Array</span>.<span class="pl-en">from</span>(<span class="pl-en">numbers</span>()) <span
                class="pl-c"><span class="pl-c">//</span> [1, 2]</span>

<span class="pl-c"><span class="pl-c">//</span> 解构赋值</span>
<span class="pl-k">let</span> [x, y] <span class="pl-k">=</span> <span class="pl-en">numbers</span>();
x <span class="pl-c"><span class="pl-c">//</span> 1</span>
y <span class="pl-c"><span class="pl-c">//</span> 2</span>

<span class="pl-c"><span class="pl-c">//</span> for...of 循环</span>
<span class="pl-k">for</span> (<span class="pl-k">let</span> n <span class="pl-k">of</span> <span
                class="pl-en">numbers</span>()) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(n)
}
<span class="pl-c"><span class="pl-c">//</span> 1</span>
<span class="pl-c"><span class="pl-c">//</span> 2</span></pre>
    </div>
    <h2><a href="#generatorprototypethrow"  class="anchor" id="user-content-generatorprototypethrow">

    </a>Generator.prototype.throw()
    </h2>
    <p>Generator 函数返回的遍历器对象，都有一个<code>throw</code>方法，可以在函数体外抛出错误，然后在 Generator 函数体内捕获。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">g</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">try</span> {
    <span class="pl-k">yield</span>;
  } <span class="pl-k">catch</span> (e) {
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>内部捕获<span
                class="pl-pds">'</span></span>, e);
  }
};

<span class="pl-k">var</span> i <span class="pl-k">=</span> <span class="pl-en">g</span>();
<span class="pl-smi">i</span>.<span class="pl-c1">next</span>();

<span class="pl-k">try</span> {
  <span class="pl-smi">i</span>.<span class="pl-en">throw</span>(<span class="pl-s"><span class="pl-pds">'</span>a<span
                class="pl-pds">'</span></span>);
  <span class="pl-smi">i</span>.<span class="pl-en">throw</span>(<span class="pl-s"><span class="pl-pds">'</span>b<span
                class="pl-pds">'</span></span>);
} <span class="pl-k">catch</span> (e) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>外部捕获<span
                class="pl-pds">'</span></span>, e);
}
<span class="pl-c"><span class="pl-c">//</span> 内部捕获 a</span>
<span class="pl-c"><span class="pl-c">//</span> 外部捕获 b</span></pre>
    </div>
    <p>上面代码中，遍历器对象<code>i</code>连续抛出两个错误。第一个错误被 Generator 函数体内的<code>catch</code>语句捕获。<code>i</code>第二次抛出错误，由于 Generator
        函数内部的<code>catch</code>语句已经执行过了，不会再捕捉到这个错误了，所以这个错误就被抛出了 Generator 函数体，被函数体外的<code>catch</code>语句捕获。</p>
    <p><code>throw</code>方法可以接受一个参数，该参数会被<code>catch</code>语句接收，建议抛出<code>Error</code>对象的实例。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">g</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">try</span> {
    <span class="pl-k">yield</span>;
  } <span class="pl-k">catch</span> (e) {
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(e);
  }
};

<span class="pl-k">var</span> i <span class="pl-k">=</span> <span class="pl-en">g</span>();
<span class="pl-smi">i</span>.<span class="pl-c1">next</span>();
<span class="pl-smi">i</span>.<span class="pl-en">throw</span>(<span class="pl-k">new</span> <span
                class="pl-en">Error</span>(<span class="pl-s"><span class="pl-pds">'</span>出错了！<span
                class="pl-pds">'</span></span>));
<span class="pl-c"><span class="pl-c">//</span> Error: 出错了！(…)</span></pre>
    </div>
    <p>
        注意，不要混淆遍历器对象的<code>throw</code>方法和全局的<code>throw</code>命令。上面代码的错误，是用遍历器对象的<code>throw</code>方法抛出的，而不是用<code>throw</code>命令抛出的。后者只能被函数体外的<code>catch</code>语句捕获。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">g</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">while</span> (<span class="pl-c1">true</span>) {
    <span class="pl-k">try</span> {
      <span class="pl-k">yield</span>;
    } <span class="pl-k">catch</span> (e) {
      <span class="pl-k">if</span> (e <span class="pl-k">!=</span> <span class="pl-s"><span
                class="pl-pds">'</span>a<span class="pl-pds">'</span></span>) <span class="pl-k">throw</span> e;
      <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>内部捕获<span
                class="pl-pds">'</span></span>, e);
    }
  }
};

<span class="pl-k">var</span> i <span class="pl-k">=</span> <span class="pl-en">g</span>();
<span class="pl-smi">i</span>.<span class="pl-c1">next</span>();

<span class="pl-k">try</span> {
  <span class="pl-k">throw</span> <span class="pl-k">new</span> <span class="pl-en">Error</span>(<span
                class="pl-s"><span class="pl-pds">'</span>a<span class="pl-pds">'</span></span>);
  <span class="pl-k">throw</span> <span class="pl-k">new</span> <span class="pl-en">Error</span>(<span
                class="pl-s"><span class="pl-pds">'</span>b<span class="pl-pds">'</span></span>);
} <span class="pl-k">catch</span> (e) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>外部捕获<span
                class="pl-pds">'</span></span>, e);
}
<span class="pl-c"><span class="pl-c">//</span> 外部捕获 [Error: a]</span></pre>
    </div>
    <p>上面代码之所以只捕获了<code>a</code>，是因为函数体外的<code>catch</code>语句块，捕获了抛出的<code>a</code>错误以后，就不会再继续<code>try</code>代码块里面剩余的语句了。
    </p>
    <p>如果 Generator 函数内部没有部署<code>try...catch</code>代码块，那么<code>throw</code>方法抛出的错误，将被外部<code>try...catch</code>代码块捕获。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">g</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">while</span> (<span class="pl-c1">true</span>) {
    <span class="pl-k">yield</span>;
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>内部捕获<span
                class="pl-pds">'</span></span>, e);
  }
};

<span class="pl-k">var</span> i <span class="pl-k">=</span> <span class="pl-en">g</span>();
<span class="pl-smi">i</span>.<span class="pl-c1">next</span>();

<span class="pl-k">try</span> {
  <span class="pl-smi">i</span>.<span class="pl-en">throw</span>(<span class="pl-s"><span class="pl-pds">'</span>a<span
                class="pl-pds">'</span></span>);
  <span class="pl-smi">i</span>.<span class="pl-en">throw</span>(<span class="pl-s"><span class="pl-pds">'</span>b<span
                class="pl-pds">'</span></span>);
} <span class="pl-k">catch</span> (e) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>外部捕获<span
                class="pl-pds">'</span></span>, e);
}
<span class="pl-c"><span class="pl-c">//</span> 外部捕获 a</span></pre>
    </div>
    <p>上面代码中，Generator 函数<code>g</code>内部没有部署<code>try...catch</code>代码块，所以抛出的错误直接被外部<code>catch</code>代码块捕获。</p>
    <p>如果 Generator 函数内部和外部，都没有部署<code>try...catch</code>代码块，那么程序将报错，直接中断执行。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">gen</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>(){
  <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>hello<span class="pl-pds">'</span></span>);
  <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>world<span class="pl-pds">'</span></span>);
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">gen</span>();
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>();
<span class="pl-smi">g</span>.<span class="pl-en">throw</span>();
<span class="pl-c"><span class="pl-c">//</span> hello</span>
<span class="pl-c"><span class="pl-c">//</span> Uncaught undefined</span></pre>
    </div>
    <p>上面代码中，<code>g.throw</code>抛出错误以后，没有任何<code>try...catch</code>代码块可以捕获这个错误，导致程序报错，中断执行。</p>
    <p><code>throw</code>方法被捕获以后，会附带执行下一条<code>yield</code>表达式。也就是说，会附带执行一次<code>next</code>方法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">gen</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>(){
  <span class="pl-k">try</span> {
    <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>a<span class="pl-pds">'</span></span>);
  } <span class="pl-k">catch</span> (e) {
    <span class="pl-c"><span class="pl-c">//</span> ...</span>
  }
  <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>b<span class="pl-pds">'</span></span>);
  <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>c<span class="pl-pds">'</span></span>);
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">gen</span>();
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> a</span>
<span class="pl-smi">g</span>.<span class="pl-en">throw</span>() <span class="pl-c"><span
                class="pl-c">//</span> b</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> c</span></pre>
    </div>
    <p>上面代码中，<code>g.throw</code>方法被捕获以后，自动执行了一次<code>next</code>方法，所以会打印<code>b</code>。另外，也可以看到，只要 Generator
        函数内部部署了<code>try...catch</code>代码块，那么遍历器的<code>throw</code>方法抛出的错误，不影响下一次遍历。</p>
    <p>另外，<code>throw</code>命令与<code>g.throw</code>方法是无关的，两者互不影响。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">gen</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>(){
  <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>hello<span class="pl-pds">'</span></span>);
  <span class="pl-k">yield</span> <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span
                class="pl-s"><span class="pl-pds">'</span>world<span class="pl-pds">'</span></span>);
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">gen</span>();
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>();

<span class="pl-k">try</span> {
  <span class="pl-k">throw</span> <span class="pl-k">new</span> <span class="pl-en">Error</span>();
} <span class="pl-k">catch</span> (e) {
  <span class="pl-smi">g</span>.<span class="pl-c1">next</span>();
}
<span class="pl-c"><span class="pl-c">//</span> hello</span>
<span class="pl-c"><span class="pl-c">//</span> world</span></pre>
    </div>
    <p>上面代码中，<code>throw</code>命令抛出的错误不会影响到遍历器的状态，所以两次执行<code>next</code>方法，都进行了正确的操作。</p>
    <p>这种函数体内捕获错误的机制，大大方便了对错误的处理。多个<code>yield</code>表达式，可以只用一个<code>try...catch</code>代码块来捕获错误。如果使用回调函数的写法，想要捕获多个错误，就不得不为每个函数内部写一个错误处理语句，现在只在
        Generator 函数内部写一次<code>catch</code>语句就可以了。</p>
    <p>Generator 函数体外抛出的错误，可以在函数体内捕获；反过来，Generator 函数体内抛出的错误，也可以被函数体外的<code>catch</code>捕获。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">foo</span>() {
  <span class="pl-k">var</span> x <span class="pl-k">=</span> <span class="pl-k">yield</span> <span
                class="pl-c1">3</span>;
  <span class="pl-k">var</span> y <span class="pl-k">=</span> <span class="pl-smi">x</span>.<span class="pl-c1">toUpperCase</span>();
  <span class="pl-k">yield</span> y;
}

<span class="pl-k">var</span> it <span class="pl-k">=</span> <span class="pl-en">foo</span>();

<span class="pl-smi">it</span>.<span class="pl-c1">next</span>(); <span class="pl-c"><span class="pl-c">//</span> { value:3, done:false }</span>

<span class="pl-k">try</span> {
  <span class="pl-smi">it</span>.<span class="pl-c1">next</span>(<span class="pl-c1">42</span>);
} <span class="pl-k">catch</span> (err) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(err);
}</pre>
    </div>
    <p>上面代码中，第二个<code>next</code>方法向函数体内传入一个参数 42，数值是没有<code>toUpperCase</code>方法的，所以会抛出一个 TypeError 错误，被函数体外的<code>catch</code>捕获。
    </p>
    <p>一旦 Generator
        执行过程中抛出错误，且没有被内部捕获，就不会再执行下去了。如果此后还调用<code>next</code>方法，将返回一个<code>value</code>属性等于<code>undefined</code>、<code>done</code>属性等于<code>true</code>的对象，即
        JavaScript 引擎认为这个 Generator 已经运行结束了。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">g</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>throwing an exception<span
                class="pl-pds">'</span></span>);
  <span class="pl-k">throw</span> <span class="pl-k">new</span> <span class="pl-en">Error</span>(<span
                class="pl-s"><span class="pl-pds">'</span>generator broke!<span class="pl-pds">'</span></span>);
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
}

<span class="pl-k">function</span> <span class="pl-en">log</span>(<span class="pl-smi">generator</span>) {
  <span class="pl-k">var</span> v;
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>starting generator<span
                class="pl-pds">'</span></span>);
  <span class="pl-k">try</span> {
    v <span class="pl-k">=</span> <span class="pl-smi">generator</span>.<span class="pl-c1">next</span>();
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>第一次运行next方法<span
                class="pl-pds">'</span></span>, v);
  } <span class="pl-k">catch</span> (err) {
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>捕捉错误<span
                class="pl-pds">'</span></span>, v);
  }
  <span class="pl-k">try</span> {
    v <span class="pl-k">=</span> <span class="pl-smi">generator</span>.<span class="pl-c1">next</span>();
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>第二次运行next方法<span
                class="pl-pds">'</span></span>, v);
  } <span class="pl-k">catch</span> (err) {
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>捕捉错误<span
                class="pl-pds">'</span></span>, v);
  }
  <span class="pl-k">try</span> {
    v <span class="pl-k">=</span> <span class="pl-smi">generator</span>.<span class="pl-c1">next</span>();
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>第三次运行next方法<span
                class="pl-pds">'</span></span>, v);
  } <span class="pl-k">catch</span> (err) {
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>捕捉错误<span
                class="pl-pds">'</span></span>, v);
  }
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>caller done<span
                class="pl-pds">'</span></span>);
}

<span class="pl-en">log</span>(<span class="pl-en">g</span>());
<span class="pl-c"><span class="pl-c">//</span> starting generator</span>
<span class="pl-c"><span class="pl-c">//</span> 第一次运行next方法 { value: 1, done: false }</span>
<span class="pl-c"><span class="pl-c">//</span> throwing an exception</span>
<span class="pl-c"><span class="pl-c">//</span> 捕捉错误 { value: 1, done: false }</span>
<span class="pl-c"><span class="pl-c">//</span> 第三次运行next方法 { value: undefined, done: true }</span>
<span class="pl-c"><span class="pl-c">//</span> caller done</span></pre>
    </div>
    <p>上面代码一共三次运行<code>next</code>方法，第二次运行的时候会抛出错误，然后第三次运行的时候，Generator 函数就已经结束了，不再执行下去了。</p>
    <h2><a href="#generatorprototypereturn"  class="anchor"
           id="user-content-generatorprototypereturn">

    </a>Generator.prototype.return()
    </h2>
    <p>Generator 函数返回的遍历器对象，还有一个<code>return</code>方法，可以返回给定的值，并且终结遍历 Generator 函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">gen</span>();

<span class="pl-smi">g</span>.<span class="pl-c1">next</span>()        <span class="pl-c"><span class="pl-c">//</span> { value: 1, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-en">return</span>(<span class="pl-s"><span class="pl-pds">'</span>foo<span
                class="pl-pds">'</span></span>) <span class="pl-c"><span class="pl-c">//</span> { value: "foo", done: true }</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>()        <span class="pl-c"><span class="pl-c">//</span> { value: undefined, done: true }</span></pre>
    </div>
    <p>
        上面代码中，遍历器对象<code>g</code>调用<code>return</code>方法后，返回值的<code>value</code>属性就是<code>return</code>方法的参数<code>foo</code>。并且，Generator
        函数的遍历就终止了，返回值的<code>done</code>属性为<code>true</code>，以后再调用<code>next</code>方法，<code>done</code>属性总是返回<code>true</code>。
    </p>
    <p>如果<code>return</code>方法调用时，不提供参数，则返回值的<code>value</code>属性为<code>undefined</code>。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
}

<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">gen</span>();

<span class="pl-smi">g</span>.<span class="pl-c1">next</span>()        <span class="pl-c"><span class="pl-c">//</span> { value: 1, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-en">return</span>() <span class="pl-c"><span class="pl-c">//</span> { value: undefined, done: true }</span></pre>
    </div>
    <p>如果 Generator 函数内部有<code>try...finally</code>代码块，那么<code>return</code>方法会推迟到<code>finally</code>代码块执行完再执行。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">numbers</span> () {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-k">try</span> {
    <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
    <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
  } <span class="pl-k">finally</span> {
    <span class="pl-k">yield</span> <span class="pl-c1">4</span>;
    <span class="pl-k">yield</span> <span class="pl-c1">5</span>;
  }
  <span class="pl-k">yield</span> <span class="pl-c1">6</span>;
}
<span class="pl-k">var</span> g <span class="pl-k">=</span> <span class="pl-en">numbers</span>();
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value: 1, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value: 2, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-en">return</span>(<span class="pl-c1">7</span>) <span class="pl-c"><span
                class="pl-c">//</span> { value: 4, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value: 5, done: false }</span>
<span class="pl-smi">g</span>.<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value: 7, done: true }</span></pre>
    </div>
    <p>上面代码中，调用<code>return</code>方法后，就开始执行<code>finally</code>代码块，然后等到<code>finally</code>代码块执行完，再执行<code>return</code>方法。
    </p>
    <h2><a href="#nextthrowreturn-的共同点"  class="anchor" id="user-content-nextthrowreturn-的共同点">

    </a>next()、throw()、return() 的共同点
    </h2>
    <p>网友 vision57 提出，<code>next()</code>、<code>throw()</code>、<code>return()</code>这三个方法本质上是同一件事，可以放在一起理解。它们的作用都是让
        Generator 函数恢复执行，并且使用不同的语句替换<code>yield</code>表达式。</p>
    <p><code>next()</code>是将<code>yield</code>表达式替换成一个值。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">const</span> <span class="pl-c1">g</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> (<span
            class="pl-smi">x</span>, <span class="pl-smi">y</span>) {
  <span class="pl-k">let</span> result <span class="pl-k">=</span> <span class="pl-k">yield</span> x <span class="pl-k">+</span> y;
  <span class="pl-k">return</span> result;
};

<span class="pl-k">const</span> <span class="pl-c1">gen</span> <span class="pl-k">=</span> <span class="pl-en">g</span>(<span
                class="pl-c1">1</span>, <span class="pl-c1">2</span>);
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>(); <span class="pl-c"><span class="pl-c">//</span> Object {value: 3, done: false}</span>

<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>(<span class="pl-c1">1</span>); <span class="pl-c"><span
                class="pl-c">//</span> Object {value: 1, done: true}</span>
<span class="pl-c"><span class="pl-c">//</span> 相当于将 let result = yield x + y</span>
<span class="pl-c"><span class="pl-c">//</span> 替换成 let result = 1;</span></pre>
    </div>
    <p>
        上面代码中，第二个<code>next(1)</code>方法就相当于将<code>yield</code>表达式替换成一个值<code>1</code>。如果<code>next</code>方法没有参数，就相当于替换成<code>undefined</code>。
    </p>
    <p><code>throw()</code>是将<code>yield</code>表达式替换成一个<code>throw</code>语句。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-smi">gen</span>.<span
            class="pl-en">throw</span>(<span class="pl-k">new</span> <span class="pl-en">Error</span>(<span
            class="pl-s"><span class="pl-pds">'</span>出错了<span class="pl-pds">'</span></span>)); <span
            class="pl-c"><span class="pl-c">//</span> Uncaught Error: 出错了</span>
<span class="pl-c"><span class="pl-c">//</span> 相当于将 let result = yield x + y</span>
<span class="pl-c"><span class="pl-c">//</span> 替换成 let result = throw(new Error('出错了'));</span></pre>
    </div>
    <p><code>return()</code>是将<code>yield</code>表达式替换成一个<code>return</code>语句。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-smi">gen</span>.<span
            class="pl-en">return</span>(<span class="pl-c1">2</span>); <span class="pl-c"><span class="pl-c">//</span> Object {value: 2, done: true}</span>
<span class="pl-c"><span class="pl-c">//</span> 相当于将 let result = yield x + y</span>
<span class="pl-c"><span class="pl-c">//</span> 替换成 let result = return 2;</span></pre>
    </div>
    <h2><a href="#yield-表达式-1"  class="anchor" id="user-content-yield-表达式-1">

    </a>yield* 表达式
    </h2>
    <p>如果在 Generator 函数内部，调用另一个 Generator 函数，默认情况下是没有效果的。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">foo</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>a<span class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>b<span class="pl-pds">'</span></span>;
}

<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">bar</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>x<span class="pl-pds">'</span></span>;
  <span class="pl-en">foo</span>();
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>y<span class="pl-pds">'</span></span>;
}

<span class="pl-k">for</span> (<span class="pl-k">let</span> v <span class="pl-k">of</span> <span
                class="pl-en">bar</span>()){
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(v);
}
<span class="pl-c"><span class="pl-c">//</span> "x"</span>
<span class="pl-c"><span class="pl-c">//</span> "y"</span></pre>
    </div>
    <p>上面代码中，<code>foo</code>和<code>bar</code>都是 Generator 函数，在<code>bar</code>里面调用<code>foo</code>，是不会有效果的。</p>
    <p>这个就需要用到<code>yield*</code>表达式，用来在一个 Generator 函数里面执行另一个 Generator 函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">bar</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>x<span class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">foo</span>();
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>y<span class="pl-pds">'</span></span>;
}

<span class="pl-c"><span class="pl-c">//</span> 等同于</span>
<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">bar</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>x<span class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>a<span class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>b<span class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>y<span class="pl-pds">'</span></span>;
}

<span class="pl-c"><span class="pl-c">//</span> 等同于</span>
<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">bar</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>x<span class="pl-pds">'</span></span>;
  <span class="pl-k">for</span> (<span class="pl-k">let</span> v <span class="pl-k">of</span> <span
                class="pl-en">foo</span>()) {
    <span class="pl-k">yield</span> v;
  }
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>y<span class="pl-pds">'</span></span>;
}

<span class="pl-k">for</span> (<span class="pl-k">let</span> v <span class="pl-k">of</span> <span
                class="pl-en">bar</span>()){
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(v);
}
<span class="pl-c"><span class="pl-c">//</span> "x"</span>
<span class="pl-c"><span class="pl-c">//</span> "a"</span>
<span class="pl-c"><span class="pl-c">//</span> "b"</span>
<span class="pl-c"><span class="pl-c">//</span> "y"</span></pre>
    </div>
    <p>再来看一个对比的例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">inner</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>hello!<span
                class="pl-pds">'</span></span>;
}

<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">outer1</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>open<span
                class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-en">inner</span>();
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>close<span
                class="pl-pds">'</span></span>;
}

<span class="pl-k">var</span> gen <span class="pl-k">=</span> <span class="pl-en">outer1</span>()
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "open"</span>
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> 返回一个遍历器对象</span>
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "close"</span>

<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">outer2</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>open<span
                class="pl-pds">'</span></span>
  <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">inner</span>()
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>close<span
                class="pl-pds">'</span></span>
}

<span class="pl-k">var</span> gen <span class="pl-k">=</span> <span class="pl-en">outer2</span>()
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "open"</span>
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "hello!"</span>
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "close"</span></pre>
    </div>
    <p>上面例子中，<code>outer2</code>使用了<code>yield*</code>，<code>outer1</code>没使用。结果就是，<code>outer1</code>返回一个遍历器对象，<code>outer2</code>返回该遍历器对象的内部值。
    </p>
    <p>从语法角度看，如果<code>yield</code>表达式后面跟的是一个遍历器对象，需要在<code>yield</code>表达式后面加上星号，表明它返回的是一个遍历器对象。这被称为<code>yield*</code>表达式。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> delegatedIterator <span
            class="pl-k">=</span> (<span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>Hello!<span
                class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>Bye!<span
                class="pl-pds">'</span></span>;
}());

<span class="pl-k">let</span> delegatingIterator <span class="pl-k">=</span> (<span class="pl-k">function</span><span
                class="pl-k">*</span> () {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>Greetings!<span
                class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span><span class="pl-k">*</span> delegatedIterator;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>Ok, bye.<span class="pl-pds">'</span></span>;
}());

<span class="pl-k">for</span>(<span class="pl-k">let</span> value <span class="pl-k">of</span> delegatingIterator) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(value);
}
<span class="pl-c"><span class="pl-c">//</span> "Greetings!</span>
<span class="pl-c"><span class="pl-c">//</span> "Hello!"</span>
<span class="pl-c"><span class="pl-c">//</span> "Bye!"</span>
<span class="pl-c"><span class="pl-c">//</span> "Ok, bye."</span></pre>
    </div>
    <p>上面代码中，<code>delegatingIterator</code>是代理者，<code>delegatedIterator</code>是被代理者。由于<code>yield*
        delegatedIterator</code>语句得到的值，是一个遍历器，所以要用星号表示。运行结果就是使用一个遍历器，遍历了多个 Generator 函数，有递归的效果。</p>
    <p><code>yield*</code>后面的 Generator 函数（没有<code>return</code>语句时），等同于在 Generator 函数内部，部署一个<code>for...of</code>循环。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">concat</span>(<span class="pl-smi">iter1</span>, <span class="pl-smi">iter2</span>) {
  <span class="pl-k">yield</span><span class="pl-k">*</span> iter1;
  <span class="pl-k">yield</span><span class="pl-k">*</span> iter2;
}

<span class="pl-c"><span class="pl-c">//</span> 等同于</span>

<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">concat</span>(<span class="pl-smi">iter1</span>, <span
                class="pl-smi">iter2</span>) {
  <span class="pl-k">for</span> (<span class="pl-k">var</span> value <span class="pl-k">of</span> iter1) {
    <span class="pl-k">yield</span> value;
  }
  <span class="pl-k">for</span> (<span class="pl-k">var</span> value <span class="pl-k">of</span> iter2) {
    <span class="pl-k">yield</span> value;
  }
}</pre>
    </div>
    <p>上面代码说明，<code>yield*</code>后面的 Generator 函数（没有<code>return</code>语句时），不过是<code>for...of</code>的一种简写形式，完全可以用后者替代前者。反之，在有<code>return</code>语句时，则需要用<code>var
        value = yield* iterator</code>的形式获取<code>return</code>语句的值。</p>
    <p>如果<code>yield*</code>后面跟着一个数组，由于数组原生支持遍历器，因此就会遍历数组成员。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>(){
  <span class="pl-k">yield</span><span class="pl-k">*</span> [<span class="pl-s"><span class="pl-pds">"</span>a<span
                class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>b<span
                class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>c<span
                class="pl-pds">"</span></span>];
}

<span class="pl-en">gen</span>().<span class="pl-c1">next</span>() <span class="pl-c"><span class="pl-c">//</span> { value:"a", done:false }</span></pre>
    </div>
    <p>上面代码中，<code>yield</code>命令后面如果不加星号，返回的是整个数组，加了星号就表示返回的是数组的遍历器对象。</p>
    <p>实际上，任何数据结构只要有 Iterator 接口，就可以被<code>yield*</code>遍历。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> read <span
            class="pl-k">=</span> (<span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>hello<span
                class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-s"><span class="pl-pds">'</span>hello<span
                class="pl-pds">'</span></span>;
})();

<span class="pl-smi">read</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "hello"</span>
<span class="pl-smi">read</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> "h"</span></pre>
    </div>
    <p>上面代码中，<code>yield</code>表达式返回整个字符串，<code>yield*</code>语句返回单个字符。因为字符串具有 Iterator 接口，所以被<code>yield*</code>遍历。</p>
    <p>如果被代理的 Generator 函数有<code>return</code>语句，那么就可以向代理它的 Generator 函数返回数据。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span class="pl-k">*</span><span
            class="pl-en">foo</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">3</span>;
  <span class="pl-k">return</span> <span class="pl-s"><span class="pl-pds">"</span>foo<span
                class="pl-pds">"</span></span>;
}

<span class="pl-k">function</span> <span class="pl-k">*</span><span class="pl-en">bar</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">1</span>;
  <span class="pl-k">var</span> v <span class="pl-k">=</span> <span class="pl-k">yield</span> <span
                class="pl-k">*</span><span class="pl-en">foo</span>();
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>( <span class="pl-s"><span class="pl-pds">"</span>v: <span
                class="pl-pds">"</span></span> <span class="pl-k">+</span> v );
  <span class="pl-k">yield</span> <span class="pl-c1">4</span>;
}

<span class="pl-k">var</span> it <span class="pl-k">=</span> <span class="pl-en">bar</span>();

<span class="pl-smi">it</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> {value: 1, done: false}</span>
<span class="pl-smi">it</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> {value: 2, done: false}</span>
<span class="pl-smi">it</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> {value: 3, done: false}</span>
<span class="pl-smi">it</span>.<span class="pl-c1">next</span>();
<span class="pl-c"><span class="pl-c">//</span> "v: foo"</span>
<span class="pl-c"><span class="pl-c">//</span> {value: 4, done: false}</span>
<span class="pl-smi">it</span>.<span class="pl-c1">next</span>()
<span class="pl-c"><span class="pl-c">//</span> {value: undefined, done: true}</span></pre>
    </div>
    <p>上面代码在第四次调用<code>next</code>方法的时候，屏幕上会有输出，这是因为函数<code>foo</code>的<code>return</code>语句，向函数<code>bar</code>提供了返回值。
    </p>
    <p>再看一个例子。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">genFuncWithReturn</span>() {
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>a<span class="pl-pds">'</span></span>;
  <span class="pl-k">yield</span> <span class="pl-s"><span class="pl-pds">'</span>b<span class="pl-pds">'</span></span>;
  <span class="pl-k">return</span> <span class="pl-s"><span class="pl-pds">'</span>The result<span
                class="pl-pds">'</span></span>;
}
<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">logReturned</span>(<span
                class="pl-smi">genObj</span>) {
  <span class="pl-k">let</span> result <span class="pl-k">=</span> <span class="pl-k">yield</span><span
                class="pl-k">*</span> genObj;
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(result);
}

[<span class="pl-k">...</span><span class="pl-en">logReturned</span>(<span class="pl-en">genFuncWithReturn</span>())]
<span class="pl-c"><span class="pl-c">//</span> The result</span>
<span class="pl-c"><span class="pl-c">//</span> 值为 [ 'a', 'b' ]</span></pre>
    </div>
    <p>
        上面代码中，存在两次遍历。第一次是扩展运算符遍历函数<code>logReturned</code>返回的遍历器对象，第二次是<code>yield*</code>语句遍历函数<code>genFuncWithReturn</code>返回的遍历器对象。这两次遍历的效果是叠加的，最终表现为扩展运算符遍历函数<code>genFuncWithReturn</code>返回的遍历器对象。所以，最后的数据表达式得到的值等于<code>[
        'a', 'b' ]</code>。但是，函数<code>genFuncWithReturn</code>的<code>return</code>语句的返回值<code>The
        result</code>，会返回给函数<code>logReturned</code>内部的<code>result</code>变量，因此会有终端输出。</p>
    <p><code>yield*</code>命令可以很方便地取出嵌套数组的所有成员。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">iterTree</span>(<span class="pl-smi">tree</span>) {
  <span class="pl-k">if</span> (<span class="pl-c1">Array</span>.<span class="pl-en">isArray</span>(tree)) {
    <span class="pl-k">for</span>(<span class="pl-k">let</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i <span
                class="pl-k">&lt;</span> <span class="pl-smi">tree</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>) {
      <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">iterTree</span>(tree[i]);
    }
  } <span class="pl-k">else</span> {
    <span class="pl-k">yield</span> tree;
  }
}

<span class="pl-k">const</span> <span class="pl-c1">tree</span> <span class="pl-k">=</span> [ <span class="pl-s"><span
                class="pl-pds">'</span>a<span class="pl-pds">'</span></span>, [<span class="pl-s"><span
                class="pl-pds">'</span>b<span class="pl-pds">'</span></span>, <span class="pl-s"><span
                class="pl-pds">'</span>c<span class="pl-pds">'</span></span>], [<span class="pl-s"><span class="pl-pds">'</span>d<span
                class="pl-pds">'</span></span>, <span class="pl-s"><span class="pl-pds">'</span>e<span
                class="pl-pds">'</span></span>] ];

<span class="pl-k">for</span>(<span class="pl-k">let</span> x <span class="pl-k">of</span> <span
                class="pl-en">iterTree</span>(tree)) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(x);
}
<span class="pl-c"><span class="pl-c">//</span> a</span>
<span class="pl-c"><span class="pl-c">//</span> b</span>
<span class="pl-c"><span class="pl-c">//</span> c</span>
<span class="pl-c"><span class="pl-c">//</span> d</span>
<span class="pl-c"><span class="pl-c">//</span> e</span></pre>
    </div>
    <p>下面是一个稍微复杂的例子，使用<code>yield*</code>语句遍历完全二叉树。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c"><span class="pl-c">//</span> 下面是二叉树的构造函数，</span>
<span class="pl-c"><span class="pl-c">//</span> 三个参数分别是左树、当前节点和右树</span>
<span class="pl-k">function</span> <span class="pl-en">Tree</span>(<span class="pl-smi">left</span>, <span
                class="pl-smi">label</span>, <span class="pl-smi">right</span>) {
  <span class="pl-c1">this</span>.<span class="pl-c1">left</span> <span class="pl-k">=</span> left;
  <span class="pl-c1">this</span>.<span class="pl-c1">label</span> <span class="pl-k">=</span> label;
  <span class="pl-c1">this</span>.<span class="pl-c1">right</span> <span class="pl-k">=</span> right;
}

<span class="pl-c"><span class="pl-c">//</span> 下面是中序（inorder）遍历函数。</span>
<span class="pl-c"><span class="pl-c">//</span> 由于返回的是一个遍历器，所以要用generator函数。</span>
<span class="pl-c"><span class="pl-c">//</span> 函数体内采用递归算法，所以左树和右树要用yield*遍历</span>
<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">inorder</span>(<span
                class="pl-smi">t</span>) {
  <span class="pl-k">if</span> (t) {
    <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">inorder</span>(<span
                class="pl-smi">t</span>.<span class="pl-c1">left</span>);
    <span class="pl-k">yield</span> <span class="pl-smi">t</span>.<span class="pl-c1">label</span>;
    <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">inorder</span>(<span
                class="pl-smi">t</span>.<span class="pl-c1">right</span>);
  }
}

<span class="pl-c"><span class="pl-c">//</span> 下面生成二叉树</span>
<span class="pl-k">function</span> <span class="pl-en">make</span>(<span class="pl-smi">array</span>) {
  <span class="pl-c"><span class="pl-c">//</span> 判断是否为叶节点</span>
  <span class="pl-k">if</span> (<span class="pl-smi">array</span>.<span class="pl-c1">length</span> <span class="pl-k">==</span> <span
                class="pl-c1">1</span>) <span class="pl-k">return</span> <span class="pl-k">new</span> <span
                class="pl-en">Tree</span>(<span class="pl-c1">null</span>, array[<span class="pl-c1">0</span>], <span
                class="pl-c1">null</span>);
  <span class="pl-k">return</span> <span class="pl-k">new</span> <span class="pl-en">Tree</span>(<span class="pl-en">make</span>(array[<span
                class="pl-c1">0</span>]), array[<span class="pl-c1">1</span>], <span
                class="pl-en">make</span>(array[<span class="pl-c1">2</span>]));
}
<span class="pl-k">let</span> tree <span class="pl-k">=</span> <span class="pl-en">make</span>([[[<span
                class="pl-s"><span class="pl-pds">'</span>a<span class="pl-pds">'</span></span>], <span
                class="pl-s"><span class="pl-pds">'</span>b<span class="pl-pds">'</span></span>, [<span
                class="pl-s"><span class="pl-pds">'</span>c<span class="pl-pds">'</span></span>]], <span
                class="pl-s"><span class="pl-pds">'</span>d<span class="pl-pds">'</span></span>, [[<span
                class="pl-s"><span class="pl-pds">'</span>e<span class="pl-pds">'</span></span>], <span
                class="pl-s"><span class="pl-pds">'</span>f<span class="pl-pds">'</span></span>, [<span
                class="pl-s"><span class="pl-pds">'</span>g<span class="pl-pds">'</span></span>]]]);

<span class="pl-c"><span class="pl-c">//</span> 遍历二叉树</span>
<span class="pl-k">var</span> result <span class="pl-k">=</span> [];
<span class="pl-k">for</span> (<span class="pl-k">let</span> node <span class="pl-k">of</span> <span class="pl-en">inorder</span>(tree)) {
  <span class="pl-smi">result</span>.<span class="pl-c1">push</span>(node);
}

result
<span class="pl-c"><span class="pl-c">//</span> ['a', 'b', 'c', 'd', 'e', 'f', 'g']</span></pre>
    </div>
    <h2><a href="#作为对象属性的-generator-函数"  class="anchor" id="user-content-作为对象属性的-generator-函数">

    </a>作为对象属性的 Generator 函数
    </h2>
    <p>如果一个对象的属性是 Generator 函数，可以简写成下面的形式。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> obj <span class="pl-k">=</span> {
  <span class="pl-k">*</span> <span class="pl-en">myGeneratorMethod</span>() {
    ···
  }
};</pre>
    </div>
    <p>上面代码中，<code>myGeneratorMethod</code>属性前面有一个星号，表示这个属性是一个 Generator 函数。</p>
    <p>它的完整形式如下，与上面的写法是等价的。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> obj <span class="pl-k">=</span> {
  <span class="pl-en">myGeneratorMethod</span><span class="pl-k">:</span> <span class="pl-k">function</span><span
                class="pl-k">*</span> () {
    <span class="pl-c"><span class="pl-c">//</span> ···</span>
  }
};</pre>
    </div>
    <h2><a href="#generator-函数的this"  class="anchor" id="user-content-generator-函数的this">

    </a>Generator 函数的<code>this</code></h2>
    <p>Generator 函数总是返回一个遍历器，ES6 规定这个遍历器是 Generator 函数的实例，也继承了 Generator 函数的<code>prototype</code>对象上的方法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">g</span>() {}

<span class="pl-smi">g</span>.<span class="pl-c1">prototype</span>.<span class="pl-en">hello</span> <span
                class="pl-k">=</span> <span class="pl-k">function</span> () {
  <span class="pl-k">return</span> <span class="pl-s"><span class="pl-pds">'</span>hi!<span
                class="pl-pds">'</span></span>;
};

<span class="pl-k">let</span> obj <span class="pl-k">=</span> <span class="pl-en">g</span>();

obj <span class="pl-k">instanceof</span> g <span class="pl-c"><span class="pl-c">//</span> true</span>
<span class="pl-smi">obj</span>.<span class="pl-en">hello</span>() <span class="pl-c"><span class="pl-c">//</span> 'hi!'</span></pre>
    </div>
    <p>上面代码表明，Generator
        函数<code>g</code>返回的遍历器<code>obj</code>，是<code>g</code>的实例，而且继承了<code>g.prototype</code>。但是，如果把<code>g</code>当作普通的构造函数，并不会生效，因为<code>g</code>返回的总是遍历器对象，而不是<code>this</code>对象。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">g</span>() {
  <span class="pl-c1">this</span>.<span class="pl-smi">a</span> <span class="pl-k">=</span> <span
                class="pl-c1">11</span>;
}

<span class="pl-k">let</span> obj <span class="pl-k">=</span> <span class="pl-en">g</span>();
<span class="pl-smi">obj</span>.<span class="pl-smi">a</span> <span class="pl-c"><span class="pl-c">//</span> undefined</span></pre>
    </div>
    <p>上面代码中，Generator 函数<code>g</code>在<code>this</code>对象上面添加了一个属性<code>a</code>，但是<code>obj</code>对象拿不到这个属性。</p>
    <p>Generator 函数也不能跟<code>new</code>命令一起用，会报错。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">F</span>() {
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-c1">x</span> <span
                class="pl-k">=</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-c1">y</span> <span
                class="pl-k">=</span> <span class="pl-c1">3</span>;
}

<span class="pl-k">new</span> <span class="pl-en">F</span>()
<span class="pl-c"><span class="pl-c">//</span> TypeError: F is not a constructor</span></pre>
    </div>
    <p>上面代码中，<code>new</code>命令跟构造函数<code>F</code>一起使用，结果报错，因为<code>F</code>不是构造函数。</p>
    <p>那么，有没有办法让 Generator 函数返回一个正常的对象实例，既可以用<code>next</code>方法，又可以获得正常的<code>this</code>？</p>
    <p>下面是一个变通方法。首先，生成一个空对象，使用<code>call</code>方法绑定 Generator 函数内部的<code>this</code>。这样，构造函数调用以后，这个空对象就是 Generator
        函数的实例对象了。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">F</span>() {
  <span class="pl-c1">this</span>.<span class="pl-smi">a</span> <span class="pl-k">=</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-smi">b</span> <span
                class="pl-k">=</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-smi">c</span> <span
                class="pl-k">=</span> <span class="pl-c1">3</span>;
}
<span class="pl-k">var</span> obj <span class="pl-k">=</span> {};
<span class="pl-k">var</span> f <span class="pl-k">=</span> <span class="pl-c1">F</span>.<span class="pl-c1">call</span>(obj);

<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: 2, done: false}</span>
<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: 3, done: false}</span>
<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: undefined, done: true}</span>

<span class="pl-smi">obj</span>.<span class="pl-smi">a</span> <span class="pl-c"><span class="pl-c">//</span> 1</span>
<span class="pl-smi">obj</span>.<span class="pl-smi">b</span> <span class="pl-c"><span class="pl-c">//</span> 2</span>
<span class="pl-smi">obj</span>.<span class="pl-smi">c</span> <span class="pl-c"><span
                class="pl-c">//</span> 3</span></pre>
    </div>
    <p>上面代码中，首先是<code>F</code>内部的<code>this</code>对象绑定<code>obj</code>对象，然后调用它，返回一个 Iterator
        对象。这个对象执行三次<code>next</code>方法（因为<code>F</code>内部有两个<code>yield</code>表达式），完成 F
        内部所有代码的运行。这时，所有内部属性都绑定在<code>obj</code>对象上了，因此<code>obj</code>对象也就成了<code>F</code>的实例。</p>
    <p>上面代码中，执行的是遍历器对象<code>f</code>，但是生成的对象实例是<code>obj</code>，有没有办法将这两个对象统一呢？</p>
    <p>一个办法就是将<code>obj</code>换成<code>F.prototype</code>。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">F</span>() {
  <span class="pl-c1">this</span>.<span class="pl-smi">a</span> <span class="pl-k">=</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-smi">b</span> <span
                class="pl-k">=</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-smi">c</span> <span
                class="pl-k">=</span> <span class="pl-c1">3</span>;
}
<span class="pl-k">var</span> f <span class="pl-k">=</span> <span class="pl-c1">F</span>.<span class="pl-c1">call</span>(<span
                class="pl-c1">F</span>.<span class="pl-c1">prototype</span>);

<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: 2, done: false}</span>
<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: 3, done: false}</span>
<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: undefined, done: true}</span>

<span class="pl-smi">f</span>.<span class="pl-smi">a</span> <span class="pl-c"><span class="pl-c">//</span> 1</span>
<span class="pl-smi">f</span>.<span class="pl-smi">b</span> <span class="pl-c"><span class="pl-c">//</span> 2</span>
<span class="pl-smi">f</span>.<span class="pl-smi">c</span> <span class="pl-c"><span
                class="pl-c">//</span> 3</span></pre>
    </div>
    <p>再将<code>F</code>改成构造函数，就可以对它执行<code>new</code>命令了。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">gen</span>() {
  <span class="pl-c1">this</span>.<span class="pl-smi">a</span> <span class="pl-k">=</span> <span class="pl-c1">1</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-smi">b</span> <span
                class="pl-k">=</span> <span class="pl-c1">2</span>;
  <span class="pl-k">yield</span> <span class="pl-c1">this</span>.<span class="pl-smi">c</span> <span
                class="pl-k">=</span> <span class="pl-c1">3</span>;
}

<span class="pl-k">function</span> <span class="pl-en">F</span>() {
  <span class="pl-k">return</span> <span class="pl-smi">gen</span>.<span class="pl-c1">call</span>(<span class="pl-smi">gen</span>.<span
                class="pl-c1">prototype</span>);
}

<span class="pl-k">var</span> f <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">F</span>();

<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: 2, done: false}</span>
<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: 3, done: false}</span>
<span class="pl-smi">f</span>.<span class="pl-c1">next</span>();  <span class="pl-c"><span class="pl-c">//</span> Object {value: undefined, done: true}</span>

<span class="pl-smi">f</span>.<span class="pl-smi">a</span> <span class="pl-c"><span class="pl-c">//</span> 1</span>
<span class="pl-smi">f</span>.<span class="pl-smi">b</span> <span class="pl-c"><span class="pl-c">//</span> 2</span>
<span class="pl-smi">f</span>.<span class="pl-smi">c</span> <span class="pl-c"><span
                class="pl-c">//</span> 3</span></pre>
    </div>
    <h2><a href="#含义"  class="anchor" id="user-content-含义">

    </a>含义
    </h2>
    <h3><a href="#generator-与状态机"  class="anchor" id="user-content-generator-与状态机">

    </a>Generator 与状态机
    </h3>
    <p>Generator 是实现状态机的最佳结构。比如，下面的<code>clock</code>函数就是一个状态机。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> ticking <span
            class="pl-k">=</span> <span class="pl-c1">true</span>;
<span class="pl-k">var</span> <span class="pl-en">clock</span> <span class="pl-k">=</span> <span
                class="pl-k">function</span>() {
  <span class="pl-k">if</span> (ticking)
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Tick!<span
                class="pl-pds">'</span></span>);
  <span class="pl-k">else</span>
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Tock!<span
                class="pl-pds">'</span></span>);
  ticking <span class="pl-k">=</span> <span class="pl-k">!</span>ticking;
}</pre>
    </div>
    <p>上面代码的<code>clock</code>函数一共有两种状态（<code>Tick</code>和<code>Tock</code>），每运行一次，就改变一次状态。这个函数如果用 Generator 实现，就是下面这样。
    </p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> <span class="pl-en">clock</span> <span
            class="pl-k">=</span> <span class="pl-k">function</span><span class="pl-k">*</span> () {
  <span class="pl-k">while</span> (<span class="pl-c1">true</span>) {
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Tick!<span
                class="pl-pds">'</span></span>);
    <span class="pl-k">yield</span>;
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-s"><span class="pl-pds">'</span>Tock!<span
                class="pl-pds">'</span></span>);
    <span class="pl-k">yield</span>;
  }
};</pre>
    </div>
    <p>上面的 Generator 实现与 ES5 实现对比，可以看到少了用来保存状态的外部变量<code>ticking</code>，这样就更简洁，更安全（状态不会被非法篡改）、更符合函数式编程的思想，在写法上也更优雅。Generator
        之所以可以不用外部变量保存状态，是因为它本身就包含了一个状态信息，即目前是否处于暂停态。</p>
    <h3><a href="#generator-与协程"  class="anchor" id="user-content-generator-与协程">

    </a>Generator 与协程
    </h3>
    <p>协程（coroutine）是一种程序运行的方式，可以理解成“协作的线程”或“协作的函数”。协程既可以用单线程实现，也可以用多线程实现。前者是一种特殊的子例程，后者是一种特殊的线程。</p>
    <p><strong>（1）协程与子例程的差异</strong></p>
    <p>
        传统的“子例程”（subroutine）采用堆栈式“后进先出”的执行方式，只有当调用的子函数完全执行完毕，才会结束执行父函数。协程与其不同，多个线程（单线程情况下，即多个函数）可以并行执行，但是只有一个线程（或函数）处于正在运行的状态，其他线程（或函数）都处于暂停态（suspended），线程（或函数）之间可以交换执行权。也就是说，一个线程（或函数）执行到一半，可以暂停执行，将执行权交给另一个线程（或函数），等到稍后收回执行权的时候，再恢复执行。这种可以并行执行、交换执行权的线程（或函数），就称为协程。</p>
    <p>从实现上看，在内存中，子例程只使用一个栈（stack），而协程是同时存在多个栈，但只有一个栈是在运行状态，也就是说，协程是以多占用内存为代价，实现多任务的并行。</p>
    <p><strong>（2）协程与普通线程的差异</strong></p>
    <p>
        不难看出，协程适合用于多任务运行的环境。在这个意义上，它与普通的线程很相似，都有自己的执行上下文、可以分享全局变量。它们的不同之处在于，同一时间可以有多个线程处于运行状态，但是运行的协程只能有一个，其他协程都处于暂停状态。此外，普通的线程是抢先式的，到底哪个线程优先得到资源，必须由运行环境决定，但是协程是合作式的，执行权由协程自己分配。</p>
    <p>由于 JavaScript
        是单线程语言，只能保持一个调用栈。引入协程以后，每个任务可以保持自己的调用栈。这样做的最大好处，就是抛出错误的时候，可以找到原始的调用栈。不至于像异步操作的回调函数那样，一旦出错，原始的调用栈早就结束。</p>
    <p>Generator 函数是 ES6 对协程的实现，但属于不完全实现。Generator 函数被称为“半协程”（semi-coroutine），意思是只有 Generator 函数的调用者，才能将程序的执行权还给
        Generator 函数。如果是完全执行的协程，任何函数都可以让暂停的协程继续执行。</p>
    <p>如果将 Generator 函数当作协程，完全可以将多个需要互相协作的任务写成 Generator 函数，它们之间使用<code>yield</code>表示式交换控制权。</p>
    <h2><a href="#应用"  class="anchor" id="user-content-应用">

    </a>应用
    </h2>
    <p>Generator 可以暂停函数执行，返回任意表达式的值。这种特点使得 Generator 有多种应用场景。</p>
    <h3><a href="#1异步操作的同步化表达"  class="anchor" id="user-content-1异步操作的同步化表达">

    </a>（1）异步操作的同步化表达
    </h3>
    <p>Generator 函数的暂停执行的效果，意味着可以把异步操作写在<code>yield</code>表达式里面，等到调用<code>next</code>方法时再往后执行。这实际上等同于不需要写回调函数了，因为异步操作的后续操作可以放在<code>yield</code>表达式下面，反正要等到调用<code>next</code>方法时再执行。所以，Generator
        函数的一个重要实际意义就是用来处理异步操作，改写回调函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">loadUI</span>() {
  <span class="pl-en">showLoadingScreen</span>();
  <span class="pl-k">yield</span> <span class="pl-en">loadUIDataAsynchronously</span>();
  <span class="pl-en">hideLoadingScreen</span>();
}
<span class="pl-k">var</span> loader <span class="pl-k">=</span> <span class="pl-en">loadUI</span>();
<span class="pl-c"><span class="pl-c">//</span> 加载UI</span>
<span class="pl-smi">loader</span>.<span class="pl-c1">next</span>()

<span class="pl-c"><span class="pl-c">//</span> 卸载UI</span>
<span class="pl-smi">loader</span>.<span class="pl-c1">next</span>()</pre>
    </div>
    <p>
        上面代码中，第一次调用<code>loadUI</code>函数时，该函数不会执行，仅返回一个遍历器。下一次对该遍历器调用<code>next</code>方法，则会显示<code>Loading</code>界面（<code>showLoadingScreen</code>），并且异步加载数据（<code>loadUIDataAsynchronously</code>）。等到数据加载完成，再一次使用<code>next</code>方法，则会隐藏<code>Loading</code>界面。可以看到，这种写法的好处是所有<code>Loading</code>界面的逻辑，都被封装在一个函数，按部就班非常清晰。
    </p>
    <p>Ajax 是典型的异步操作，通过 Generator 函数部署 Ajax 操作，可以用同步的方式表达。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">main</span>() {
  <span class="pl-k">var</span> result <span class="pl-k">=</span> <span class="pl-k">yield</span> <span class="pl-en">request</span>(<span
                class="pl-s"><span class="pl-pds">"</span>http://some.url<span class="pl-pds">"</span></span>);
  <span class="pl-k">var</span> resp <span class="pl-k">=</span> <span class="pl-c1">JSON</span>.<span class="pl-c1">parse</span>(result);
    <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-smi">resp</span>.<span
                class="pl-c1">value</span>);
}

<span class="pl-k">function</span> <span class="pl-en">request</span>(<span class="pl-smi">url</span>) {
  <span class="pl-en">makeAjaxCall</span>(url, <span class="pl-k">function</span>(<span class="pl-smi">response</span>){
    <span class="pl-smi">it</span>.<span class="pl-c1">next</span>(response);
  });
}

<span class="pl-k">var</span> it <span class="pl-k">=</span> <span class="pl-en">main</span>();
<span class="pl-smi">it</span>.<span class="pl-c1">next</span>();</pre>
    </div>
    <p>上面代码的<code>main</code>函数，就是通过 Ajax
        操作获取数据。可以看到，除了多了一个<code>yield</code>，它几乎与同步操作的写法完全一样。注意，<code>makeAjaxCall</code>函数中的<code>next</code>方法，必须加上<code>response</code>参数，因为<code>yield</code>表达式，本身是没有值的，总是等于<code>undefined</code>。
    </p>
    <p>下面是另一个例子，通过 Generator 函数逐行读取文本文件。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">numbers</span>() {
  <span class="pl-k">let</span> file <span class="pl-k">=</span> <span class="pl-k">new</span> <span class="pl-en">FileReader</span>(<span
                class="pl-s"><span class="pl-pds">"</span>numbers.txt<span class="pl-pds">"</span></span>);
  <span class="pl-k">try</span> {
    <span class="pl-k">while</span>(<span class="pl-k">!</span><span class="pl-smi">file</span>.<span
                class="pl-smi">eof</span>) {
      <span class="pl-k">yield</span> <span class="pl-c1">parseInt</span>(<span class="pl-smi">file</span>.<span
                class="pl-en">readLine</span>(), <span class="pl-c1">10</span>);
    }
  } <span class="pl-k">finally</span> {
    <span class="pl-smi">file</span>.<span class="pl-c1">close</span>();
  }
}</pre>
    </div>
    <p>上面代码打开文本文件，使用<code>yield</code>表达式可以手动逐行读取文件。</p>
    <h3><a href="#2控制流管理"  class="anchor" id="user-content-2控制流管理">

    </a>（2）控制流管理
    </h3>
    <p>如果有一个多步操作非常耗时，采用回调函数，可能会写成下面这样。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-en">step1</span>(<span class="pl-k">function</span> (<span
            class="pl-smi">value1</span>) {
  <span class="pl-en">step2</span>(value1, <span class="pl-k">function</span>(<span class="pl-smi">value2</span>) {
    <span class="pl-en">step3</span>(value2, <span class="pl-k">function</span>(<span class="pl-smi">value3</span>) {
      <span class="pl-en">step4</span>(value3, <span class="pl-k">function</span>(<span class="pl-smi">value4</span>) {
        <span class="pl-c"><span class="pl-c">//</span> Do something with value4</span>
      });
    });
  });
});</pre>
    </div>
    <p>采用 Promise 改写上面的代码。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-c1">Promise</span>.<span
            class="pl-en">resolve</span>(step1)
  .<span class="pl-en">then</span>(step2)
  .<span class="pl-en">then</span>(step3)
  .<span class="pl-en">then</span>(step4)
  .<span class="pl-en">then</span>(<span class="pl-k">function</span> (<span class="pl-smi">value4</span>) {
    <span class="pl-c"><span class="pl-c">//</span> Do something with value4</span>
  }, <span class="pl-k">function</span> (<span class="pl-smi">error</span>) {
    <span class="pl-c"><span class="pl-c">//</span> Handle any error from step1 through step4</span>
  })
  .<span class="pl-en">done</span>();</pre>
    </div>
    <p>上面代码已经把回调函数，改成了直线执行的形式，但是加入了大量 Promise 的语法。Generator 函数可以进一步改善代码运行流程。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">longRunningTask</span>(<span class="pl-smi">value1</span>) {
  <span class="pl-k">try</span> {
    <span class="pl-k">var</span> value2 <span class="pl-k">=</span> <span class="pl-k">yield</span> <span
                class="pl-en">step1</span>(value1);
    <span class="pl-k">var</span> value3 <span class="pl-k">=</span> <span class="pl-k">yield</span> <span
                class="pl-en">step2</span>(value2);
    <span class="pl-k">var</span> value4 <span class="pl-k">=</span> <span class="pl-k">yield</span> <span
                class="pl-en">step3</span>(value3);
    <span class="pl-k">var</span> value5 <span class="pl-k">=</span> <span class="pl-k">yield</span> <span
                class="pl-en">step4</span>(value4);
    <span class="pl-c"><span class="pl-c">//</span> Do something with value4</span>
  } <span class="pl-k">catch</span> (e) {
    <span class="pl-c"><span class="pl-c">//</span> Handle any error from step1 through step4</span>
  }
}</pre>
    </div>
    <p>然后，使用一个函数，按次序自动执行所有步骤。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-en">scheduler</span>(<span class="pl-en">longRunningTask</span>(initialValue));

<span class="pl-k">function</span> <span class="pl-en">scheduler</span>(<span class="pl-smi">task</span>) {
  <span class="pl-k">var</span> taskObj <span class="pl-k">=</span> <span class="pl-smi">task</span>.<span
                class="pl-c1">next</span>(<span class="pl-smi">task</span>.<span class="pl-c1">value</span>);
  <span class="pl-c"><span class="pl-c">//</span> 如果Generator函数未结束，就继续调用</span>
  <span class="pl-k">if</span> (<span class="pl-k">!</span><span class="pl-smi">taskObj</span>.<span
                class="pl-smi">done</span>) {
    <span class="pl-smi">task</span>.<span class="pl-c1">value</span> <span class="pl-k">=</span> <span class="pl-smi">taskObj</span>.<span
                class="pl-c1">value</span>
    <span class="pl-en">scheduler</span>(task);
  }
}</pre>
    </div>
    <p>注意，上面这种做法，只适合同步操作，即所有的<code>task</code>都必须是同步的，不能有异步操作。因为这里的代码一得到返回值，就继续往下执行，没有判断异步操作何时完成。如果要控制异步的操作流程，详见后面的《异步操作》一章。
    </p>
    <p>下面，利用<code>for...of</code>循环会自动依次执行<code>yield</code>命令的特性，提供一种更一般的控制流管理的方法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> steps <span class="pl-k">=</span> [step1Func, step2Func, step3Func];

<span class="pl-k">function</span> <span class="pl-k">*</span><span class="pl-en">iterateSteps</span>(<span
                class="pl-smi">steps</span>){
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i<span
                class="pl-k">&lt;</span> <span class="pl-smi">steps</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>){
    <span class="pl-k">var</span> step <span class="pl-k">=</span> steps[i];
    <span class="pl-k">yield</span> <span class="pl-en">step</span>();
  }
}</pre>
    </div>
    <p>上面代码中，数组<code>steps</code>封装了一个任务的多个步骤，Generator 函数<code>iterateSteps</code>则是依次为这些步骤加上<code>yield</code>命令。</p>
    <p>将任务分解成步骤之后，还可以将项目分解成多个依次执行的任务。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">let</span> jobs <span class="pl-k">=</span> [job1, job2, job3];

<span class="pl-k">function</span><span class="pl-k">*</span> <span class="pl-en">iterateJobs</span>(<span
                class="pl-smi">jobs</span>){
  <span class="pl-k">for</span> (<span class="pl-k">var</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i<span
                class="pl-k">&lt;</span> <span class="pl-smi">jobs</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>){
    <span class="pl-k">var</span> job <span class="pl-k">=</span> jobs[i];
    <span class="pl-k">yield</span><span class="pl-k">*</span> <span class="pl-en">iterateSteps</span>(<span
                class="pl-smi">job</span>.<span class="pl-smi">steps</span>);
  }
}</pre>
    </div>
    <p>上面代码中，数组<code>jobs</code>封装了一个项目的多个任务，Generator 函数<code>iterateJobs</code>则是依次为这些任务加上<code>yield*</code>命令。</p>
    <p>最后，就可以用<code>for...of</code>循环一次性依次执行所有任务的所有步骤。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">for</span> (<span
            class="pl-k">var</span> step <span class="pl-k">of</span> <span class="pl-en">iterateJobs</span>(jobs)){
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(<span class="pl-smi">step</span>.<span
                class="pl-c1">id</span>);
}</pre>
    </div>
    <p>再次提醒，上面的做法只能用于所有步骤都是同步操作的情况，不能有异步操作的步骤。如果想要依次执行异步的步骤，必须使用后面的《异步操作》一章介绍的方法。</p>
    <p><code>for...of</code>的本质是一个<code>while</code>循环，所以上面的代码实质上执行的是下面的逻辑。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">var</span> it <span class="pl-k">=</span> <span
            class="pl-en">iterateJobs</span>(jobs);
<span class="pl-k">var</span> res <span class="pl-k">=</span> <span class="pl-smi">it</span>.<span
                class="pl-c1">next</span>();

<span class="pl-k">while</span> (<span class="pl-k">!</span><span class="pl-smi">res</span>.<span
                class="pl-smi">done</span>){
  <span class="pl-k">var</span> result <span class="pl-k">=</span> <span class="pl-smi">res</span>.<span class="pl-c1">value</span>;
  <span class="pl-c"><span class="pl-c">//</span> ...</span>
  res <span class="pl-k">=</span> <span class="pl-smi">it</span>.<span class="pl-c1">next</span>();
}</pre>
    </div>
    <h3><a href="#3部署-iterator-接口"  class="anchor" id="user-content-3部署-iterator-接口">

    </a>（3）部署 Iterator 接口
    </h3>
    <p>利用 Generator 函数，可以在任意对象上部署 Iterator 接口。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">iterEntries</span>(<span class="pl-smi">obj</span>) {
  <span class="pl-k">let</span> keys <span class="pl-k">=</span> <span class="pl-c1">Object</span>.<span class="pl-c1">keys</span>(obj);
  <span class="pl-k">for</span> (<span class="pl-k">let</span> i<span class="pl-k">=</span><span class="pl-c1">0</span>; i <span
                class="pl-k">&lt;</span> <span class="pl-smi">keys</span>.<span class="pl-c1">length</span>; i<span
                class="pl-k">++</span>) {
    <span class="pl-k">let</span> key <span class="pl-k">=</span> keys[i];
    <span class="pl-k">yield</span> [key, obj[key]];
  }
}

<span class="pl-k">let</span> myObj <span class="pl-k">=</span> { foo<span class="pl-k">:</span> <span
                class="pl-c1">3</span>, bar<span class="pl-k">:</span> <span class="pl-c1">7</span> };

<span class="pl-k">for</span> (<span class="pl-k">let</span> [key, value] <span class="pl-k">of</span> <span
                class="pl-en">iterEntries</span>(myObj)) {
  <span class="pl-en">console</span>.<span class="pl-c1">log</span>(key, value);
}

<span class="pl-c"><span class="pl-c">//</span> foo 3</span>
<span class="pl-c"><span class="pl-c">//</span> bar 7</span></pre>
    </div>
    <p>上述代码中，<code>myObj</code>是一个普通对象，通过<code>iterEntries</code>函数，就有了 Iterator 接口。也就是说，可以在任意对象上部署<code>next</code>方法。
    </p>
    <p>下面是一个对数组部署 Iterator 接口的例子，尽管数组原生具有这个接口。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span><span class="pl-k">*</span> <span
            class="pl-en">makeSimpleGenerator</span>(<span class="pl-smi">array</span>){
  <span class="pl-k">var</span> nextIndex <span class="pl-k">=</span> <span class="pl-c1">0</span>;

  <span class="pl-k">while</span>(nextIndex <span class="pl-k">&lt;</span> <span class="pl-smi">array</span>.<span
                class="pl-c1">length</span>){
    <span class="pl-k">yield</span> array[nextIndex<span class="pl-k">++</span>];
  }
}

<span class="pl-k">var</span> gen <span class="pl-k">=</span> <span class="pl-en">makeSimpleGenerator</span>([<span
                class="pl-s"><span class="pl-pds">'</span>yo<span class="pl-pds">'</span></span>, <span
                class="pl-s"><span class="pl-pds">'</span>ya<span class="pl-pds">'</span></span>]);

<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> 'yo'</span>
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-c1">value</span> <span
                class="pl-c"><span class="pl-c">//</span> 'ya'</span>
<span class="pl-smi">gen</span>.<span class="pl-c1">next</span>().<span class="pl-smi">done</span>  <span
                class="pl-c"><span class="pl-c">//</span> true</span></pre>
    </div>
    <h3><a href="#4作为数据结构"  class="anchor" id="user-content-4作为数据结构">

    </a>（4）作为数据结构
    </h3>
    <p>Generator 可以看作是数据结构，更确切地说，可以看作是一个数组结构，因为 Generator 函数可以返回一系列的值，这意味着它可以对任意表达式，提供类似数组的接口。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span class="pl-k">*</span><span
            class="pl-en">doStuff</span>() {
  <span class="pl-k">yield</span> <span class="pl-smi">fs</span>.<span class="pl-smi">readFile</span>.<span
                class="pl-en">bind</span>(<span class="pl-c1">null</span>, <span class="pl-s"><span
                class="pl-pds">'</span>hello.txt<span class="pl-pds">'</span></span>);
  <span class="pl-k">yield</span> <span class="pl-smi">fs</span>.<span class="pl-smi">readFile</span>.<span
                class="pl-en">bind</span>(<span class="pl-c1">null</span>, <span class="pl-s"><span
                class="pl-pds">'</span>world.txt<span class="pl-pds">'</span></span>);
  <span class="pl-k">yield</span> <span class="pl-smi">fs</span>.<span class="pl-smi">readFile</span>.<span
                class="pl-en">bind</span>(<span class="pl-c1">null</span>, <span class="pl-s"><span
                class="pl-pds">'</span>and-such.txt<span class="pl-pds">'</span></span>);
}</pre>
    </div>
    <p>上面代码就是依次返回三个函数，但是由于使用了 Generator 函数，导致可以像处理数组那样，处理这三个返回的函数。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">for</span> (task <span
            class="pl-k">of</span> <span class="pl-en">doStuff</span>()) {
  <span class="pl-c"><span class="pl-c">//</span> task是一个函数，可以像回调函数那样使用它</span>
}</pre>
    </div>
    <p>实际上，如果用 ES5 表达，完全可以用数组模拟 Generator 的这种用法。</p>
    <div class="highlight highlight-source-js"><pre><span class="pl-k">function</span> <span
            class="pl-en">doStuff</span>() {
  <span class="pl-k">return</span> [
    <span class="pl-smi">fs</span>.<span class="pl-smi">readFile</span>.<span class="pl-en">bind</span>(<span
                class="pl-c1">null</span>, <span class="pl-s"><span class="pl-pds">'</span>hello.txt<span
                class="pl-pds">'</span></span>),
    <span class="pl-smi">fs</span>.<span class="pl-smi">readFile</span>.<span class="pl-en">bind</span>(<span
                class="pl-c1">null</span>, <span class="pl-s"><span class="pl-pds">'</span>world.txt<span
                class="pl-pds">'</span></span>),
    <span class="pl-smi">fs</span>.<span class="pl-smi">readFile</span>.<span class="pl-en">bind</span>(<span
                class="pl-c1">null</span>, <span class="pl-s"><span class="pl-pds">'</span>and-such.txt<span
                class="pl-pds">'</span></span>)
  ];
}</pre>
    </div>
    <p>上面的函数，可以用一模一样的<code>for...of</code>循环处理！两相一比较，就不难看出 Generator 使得数据或者操作，具备了类似数组的接口。</p>
</div>
</body>
</html>
